package com.jhx.common.http;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.view.View;

import com.google.gson.JsonParseException;
import com.jhx.common.utils.SystemUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.widget.CommonDialog;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

import me.foji.lifecyclebinder.LifeCycleBinder;
import me.foji.lifecyclebinder.OnLifeCycleChangedListener;
import retrofit2.HttpException;
import retrofit2.Response;

/**
 * 统一处理Http回调
 *
 * @author jack 2017-05-05 15:27
 */
public class HttpCallback<T> implements OnLifeCycleChangedListener{
    private CommonDialog mDialog;
    private Activity mActivity;
    private ResponseCallback mCallback;
    /**
     * 是否显示统一的错误
     */
    private boolean mShowError;

    public HttpCallback(Activity activity, ResponseCallback callback, boolean showError) {
        mCallback = callback;
        mShowError = showError;
        if(activity != null) {
            mActivity = activity;
            if(Build.VERSION.SDK_INT >= 17 && !activity.isDestroyed()) {
                LifeCycleBinder.bind(mActivity, this);
            }
        }
    }

    public final void onResponse(String url, Response<HttpResponse<T>> response) {
        if (!response.isSuccessful() || response.body() == null) {
            showErrorDialog(mActivity, "网络访问异常");
            if (mCallback != null) {
                mCallback.onError(url, response.code(), response.message());
            }
            return;
        }
        if (response.body().getCode() == HttpResponse.CODE_SUCCESS) {
            onSuccess(url, response.body().getData());
        } else {
            onBusinessError(url, response.body().getCode(), response.body().getMsg());
        }
    }

    public final void onFailure(String url, Throwable t) {
        String errorMsg = "";
        int errorCode = 0;
        if (t instanceof JsonParseException ||
                t instanceof JSONException ||
                t instanceof ParseException) {
            errorMsg = "数据解析异常";
            errorCode = HttpResponse.CODE_JSON_PARSE_ERR;
        } else if (t instanceof HttpException) {
            switch (((HttpException) t).response().code()) {
                case HttpCode.NOT_FOUND:
                case HttpCode.REQUEST_TIMEOUT:
                case HttpCode.GATEWAY_TIMEOUT:
                case HttpCode.INTERNAL_SERVER_ERROR:
                case HttpCode.BAD_GATEWAY:
                case HttpCode.SERVICE_UNAVAILABLE:
                    errorMsg = "服务器繁忙，请稍后再试";
                    errorCode = ((HttpException) t).response().code();
                    break;
                default:

                    break;
            }
        } else if (t instanceof UnknownHostException) {
            errorMsg = "网络连接错误，请检查网络";
            errorCode = HttpCode.DNS_ERROR;
        } else if (!SystemUtil.isNetworkAvaliable() && t instanceof ConnectException) {
            errorMsg = "网络连接错误，请检查网络";
            errorCode = HttpCode.NETWORK_NOT_CONNECTED;
        } else {
            errorMsg = "服务器繁忙，请稍后重试";
            errorCode = HttpCode.UNKNOWN;
        }
        showErrorDialog(mActivity, errorMsg);
        if (mCallback != null) {
            mCallback.onError(url, errorCode, errorMsg);
        }
    }

    /**
     * 业务请求成功
     */
    public void onSuccess(String url, T data) {
        if (mCallback != null) {
            mCallback.onSuccess(url, data);
        }
    }

    /**
     * 业务处理异常
     */
    public void onBusinessError(String url, int errorCode, String errorMsg) {
        if (mShowError) {
            if (errorCode == HttpResponse.CODE_NOT_LOGIN) {
                if(mActivity != null && !mActivity.isFinishing()) {
                    if(mDialog == null) {
                        mDialog = new CommonDialog(mActivity);
                    }
                    mDialog.dismiss();
                    mDialog.setMessage("会话过期，请重新登录");
                    mDialog.getCancelText().setVisibility(View.VISIBLE);
                    mDialog.setOnClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onConfirmClick(View view) {
                            Intent intent = new Intent();
                            intent.setAction("com.jhx.login");
                            mActivity.startActivity(intent);
                        }

                        @Override
                        public void onCancelClick(View view) {
                            if (mActivity != null) {
                                mActivity.finish();
                            }
                        }
                    });
                    if(!mDialog.isShowing()) {
                        mDialog.show();
                    }
                }
            } else {
                showErrorDialog(mActivity, errorMsg);
            }
        }
        if (mCallback != null) {
            mCallback.onError(url, errorCode, errorMsg);
        }
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {

    }

    @Override
    public void onDestroy() {
        recycler();
    }

    public void recycler() {
        if(mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
        mActivity = null;
    }

    private void showErrorDialog(Activity activity, String errorMsg) {
        if(activity != null && !activity.isFinishing()) {
          ToastUtil.getInstance().showToast(activity, errorMsg);
        }
    }
}
